package com.qf.smsplatform.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：郝国栋
 * 项目名：IntelliJ IDEA
 * 时间:2020/8/30  20:33
 * 描述:
 */
@Configuration
public class ElasticsearchConfig {

    @Value("${spring.elasticsearch.hostAndPort}")
    private String hostAndPort;
    @Bean
    public RestHighLevelClient client(){

        // 封装es的ip和端口到一个List集合中
        List<HttpHost> httpHostList = new ArrayList<>();
        String[] hostAndPortArray = hostAndPort.split(",");
        for (String hostAndPort : hostAndPortArray) {
            int index = hostAndPort.indexOf(":");
            HttpHost httpHost = new HttpHost(hostAndPort.substring(0,index),Integer.valueOf(hostAndPort.substring(index+1)));
            httpHostList.add(httpHost);
        }


        // 创建restClientBuilder,并设置连接信息
        RestClientBuilder restClientBuilder = RestClient.builder(httpHostList.toArray(new HttpHost[httpHostList.size()]));
        //  创建RestHighLevelClient
        RestHighLevelClient client = new RestHighLevelClient(restClientBuilder);
        // 返回
        return client;
    }
}
